package com.meterhuang.thread.foobar;

/**
 * synchronized + 标志位 + 唤醒
 *
 * @author meterhuang
 * @date 2021/09/08 17:37
 */
public class FooBarSynchronized {

	private int n;

	/**
	 * 	标志位，控制执行顺序，true执行printFoo，false执行printBar
 	 */
	private volatile boolean type = true;

	private final Object obj = new Object();

	public FooBarSynchronized(int n) {
		this.n = n;
	}

	public void foo(Runnable printFoo) throws InterruptedException {
		for (int i = 0; i < n; i++) {
			synchronized (obj) {
				while(!type){
					System.out.println(Thread.currentThread().getName() + ":foo waiting...");
					obj.wait();
				}
				printFoo.run();
				type = false;
				obj.notifyAll();
			}
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {
		for (int i = 0; i < n; i++) {
			synchronized (obj) {
				while (type) {
					obj.wait();
				}
				printBar.run();
				type = true;
				obj.notify();
			}
		}
	}

}
